package baidu.com.matedemo.network;

import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.baidu.android.common.logging.Log;
import com.baidu.duer.libcore.adapter.CommonAdapter;
import com.baidu.duer.libcore.adapter.ViewHolder;
import com.baidu.duer.libcore.module.permission.PermissionHelper;
import com.baidu.duer.libcore.util.ConsoleLogger;
import com.baidu.duer.libcore.util.ToastUtil;
import com.baidu.duer.libcore.view.DuAlertDialog;
import com.baidu.duer.smartmate.duerlink.bean.DuerApDevice;
import com.baidu.duer.smartmate.duerlink.bean.DuerlinkError;
import com.baidu.duer.smartmate.duerlink.config.DuerlinkConfigManager;
import com.baidu.duer.smartmate.duerlink.config.DuerlinkConfigState;
import com.baidu.duer.smartmate.duerlink.config.IDuerlinkConfigListener;
import com.baidu.duer.smartmate.duerlink.discovery.DuerlinkApDiscoveryError;
import com.baidu.duer.smartmate.duerlink.discovery.DuerlinkDiscoveryManager;
import com.baidu.duer.smartmate.duerlink.discovery.IDuerlinkApDiscoveryListener;
import com.baidu.duer.smartmate.out.DuerDevice;
import com.baidu.duer.smartmate.out.oauth.IResponseCallback;

import java.util.ArrayList;
import java.util.List;

import baidu.com.matedemo.DemoApp;
import baidu.com.matedemo.R;
import baidu.com.matedemo.base.BaseActivity;
import baidu.com.matedemo.base.Utils;
import baidu.com.matedemo.pair.DevicePairWrapper;
import baidu.com.matedemo.pair.OauthType;
import baidu.com.matedemo.util.DemoUtils;

public class WifiConfigurationActivity extends BaseActivity {
    private DuerlinkDiscoveryManager duerlinkDiscoveryManager = null;
    private DuerlinkConfigManager duerlinkConfigManager = null;
    private EditText ssidEditText = null;
    private EditText passwordEditText = null;
    private ArrayList<String> logList = null;
    private CommonAdapter<String> logAdapter = null;
    private ListView logListView = null;
    private ArrayList<DuerApDevice> apDeviceList = null;
    private CommonAdapter<DuerApDevice> apDeviceAdapter = null;
    private ListView apDeviceListView = null;
    private DevicePairWrapper pairWrapper = null;
    private static final int REQUEST_CODE_LOCATION_SETTINGS = 1;
    private static final int REQUEST_CODE_ACCESS_COARSE_LOCATION = 2;
    private static final int REQUEST_CODE_WRITE_SETTINGS = 3;

    @Override
    public View onCreateContentViewCompat(LayoutInflater inflater, ViewGroup viewGroup, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.wifi_configuration, viewGroup, false);
    }

    @Override
    public void onContentViewCreated(View view) {
        super.onContentViewCreated(view);
        TextView oauthView = (TextView) findViewById(R.id.oauth_view);
        oauthView.setText("当前选择为");
        OauthType oauthType = DemoApp.getInstance().getOauthType();
        if (OauthType.AUTHORIZATION_CODE.equals(oauthType)) {
            oauthView.append("合作对接产品，采用oauth标准授权方式，请确定已向度秘团队申请开通授权");
        } else if (OauthType.PRIVILEGE_OAUTH.equals(oauthType)) {
            oauthView.append("百度自有产品，采用privilege授权方式，请确定已向度秘团队申请开通授权");
        } else if (OauthType.DEVICE_CODE.equals(oauthType)) {
            oauthView.append("普通开发者产品，采用device code授权方式");
        }
        ssidEditText = (EditText) findViewById(R.id.ssid_edit_text);
        passwordEditText = (EditText) findViewById(R.id.password_edit_text);
        apDeviceListView = (ListView) findViewById(R.id.device_list_view);
        logListView = (ListView) findViewById(R.id.log_list_view);
        duerlinkDiscoveryManager = new DuerlinkDiscoveryManager(getApplicationContext());
        duerlinkConfigManager = new DuerlinkConfigManager(getApplicationContext());
        apDeviceList = new ArrayList<>();

        WifiManager wifiManager = (WifiManager) view.getContext().getApplicationContext().getSystemService(WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        ssidEditText.setText(Utils.removeQuote(wifiInfo.getSSID()));

        // 确保有Location权限以获取Wi-Fi/BLE扫描结果
        if (!PermissionHelper.hasPermission(this, "android.permission.ACCESS_COARSE_LOCATION")) {
            PermissionHelper.requestPermission(this,
                    REQUEST_CODE_ACCESS_COARSE_LOCATION,
                    new String[]{"android.permission.ACCESS_COARSE_LOCATION"},
                    R.string.request_location_permission,
                    new PermissionHelper.Listener() {
                        @Override
                        public void onSucceed() {
                            Log.i(WifiConfigurationActivity.class.getSimpleName(), "got location permission");
                            onGotLocationPermission();
                        }

                        @Override
                        public void onFailed() {
                        }
                    });
        } else {
            Log.i(WifiConfigurationActivity.class.getSimpleName(), "already has location permission");
            onGotLocationPermission();
        }

        apDeviceAdapter = new CommonAdapter<DuerApDevice>(this, R.layout.item_function, apDeviceList) {
            @Override
            protected void convert(ViewHolder viewHolder, DuerApDevice duerApDevice, int i) {
                viewHolder.setText(R.id.text_view, duerApDevice.getSsid());
            }
        };
        apDeviceListView.setAdapter(apDeviceAdapter);
        apDeviceAdapter.notifyDataSetChanged();
        apDeviceListView.setOnItemClickListener(getApListener());

        logList = new ArrayList<>();
        logAdapter = new CommonAdapter<String>(this, R.layout.item_function, logList) {
            @Override
            protected void convert(ViewHolder viewHolder, String s, int i) {
                viewHolder.setText(R.id.text_view, s);
            }
        };
        logListView.setAdapter(logAdapter);
    }

    @Override
    protected void onStop() {
        super.onStop();
        // 重要！退出页面时，即时注销不再需要的回调！
        if (duerlinkDiscoveryManager != null) {
            duerlinkDiscoveryManager.stopApDiscovery();
        }
        if (duerlinkConfigManager != null) {
            duerlinkConfigManager.stopConfig();
        }
        if (pairWrapper != null) {
            pairWrapper.stopPair();
        }
    }

    private IDuerlinkApDiscoveryListener getApDiscoveryListener() {
        return new IDuerlinkApDiscoveryListener() {
            @Override
            public void onDiscovery(DuerApDevice device) {
                Log.i(WifiConfigurationActivity.class.getSimpleName(), "onDiscovery:" + device.getSsid());
                apDeviceList.add(device);
                apDeviceAdapter.notifyDataSetChanged();
            }

            @Override
            public void onDiscoveryComplete(List<DuerApDevice> devices) {

            }

            @Override
            public void onDiscoveryFail(DuerlinkApDiscoveryError error) {

            }
        };
    }

    private AdapterView.OnItemClickListener getApListener() {
        return new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                String ssid = ssidEditText.getText().toString().trim();
                if (TextUtils.isEmpty(ssid)) {
                    ToastUtil.toastWarnning(WifiConfigurationActivity.this, "请填写WIFI名称");
                    return;
                }
                String pwd = passwordEditText.getText().toString().trim();
                if (TextUtils.isEmpty(pwd)) {
                    ToastUtil.toastWarnning(WifiConfigurationActivity.this, "请填写WIFI密码");
                    return;
                }
                if (!Utils.verifyWifiPwd(pwd)) {
                    ToastUtil.toastWarnning(WifiConfigurationActivity.this, "请正确填写WIFI密码");
                    return;
                }

                showProgressBar();
                DuerApDevice duerApDevice = apDeviceList.get(i);
                duerlinkConfigManager.startConfig(duerApDevice,
                        ssidEditText.getText().toString(),
                        passwordEditText.getText().toString(),
                        new IDuerlinkConfigListener() {
                            @Override
                            public void onSuccess(final DuerDevice device) {
                                logList.add("wifi  config success");
                                logAdapter.notifyDataSetChanged();
                                ToastUtil.toastSuccess(WifiConfigurationActivity.this, "配网成功");
                                if (DemoApp.getInstance().getOauthType() == null) {
                                    // 仅配网，不授权
                                    DemoApp.getInstance().addDuerDevice(device);
                                    DemoApp.getInstance().setCurrentDevice(device);
                                    finish();
                                    return;
                                }

                                //配对
                                IResponseCallback responseCallback = new IResponseCallback() {
                                    @Override
                                    public void onSuccess() {
                                        dismissProgressBar();
                                        // 配网完成，跳转到授权页面
                                        DemoApp.getInstance().addDuerDevice(device);
                                        DemoApp.getInstance().setCurrentDevice(device);
                                        ToastUtil.toastSuccess(WifiConfigurationActivity.this, "授权成功");
                                        finish();
                                    }

                                    @Override
                                    public void onError(long status, String msg) {
                                        dismissProgressBar();
                                        ToastUtil.toastSuccess(WifiConfigurationActivity.this, "授权失败");
                                    }
                                };

                                pairWrapper = new DevicePairWrapper();
                                pairWrapper.startPair(WifiConfigurationActivity.this,
                                        DemoApp.getInstance().getOauthType(),
                                        device,
                                        responseCallback);
                            }

                            @Override
                            public void onFail(DuerlinkError error) {
                                dismissProgressBar();
                                logList.add("wifi config fail: " + error);
                                logAdapter.notifyDataSetChanged();
                            }

                            @Override
                            public void onStateChanged(DuerlinkConfigState state) {
                                logList.add(state.toString());
                                logAdapter.notifyDataSetChanged();
                            }
                        });
            }
        };
    }

    private void onGotLocationPermission() {
        if (DemoUtils.isLocationEnabled(this)) {
            onLocationSettingEnabled();
        } else {
            enableLocationSetting();
        }
    }

    private void enableLocationSetting() {
        Intent locationIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        this.startActivityForResult(locationIntent, REQUEST_CODE_LOCATION_SETTINGS);
    }

    private void onLocationSettingEnabled() {
        // ConnectivityManager.requestNetwork需要WRITE_SETTINGS权限（socket绑定wifi链路）
        // 针对android6.0中错误的把WRITE_SETTINGS当作敏感权限的bug进行workaround(此问题google在6.0.1中已修复)
        // 参考https://stackoverflow.com/questions/32083410/cant-get-write-settings-permission/32083622#32083622
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.M
                && "6.0".equals(Build.VERSION.RELEASE)
                && !Settings.System.canWrite(this)) {
            requestWriteSettingsPermission();
        } else {
            onGotWriteSettingsPermission();
        }
    }

    private void requestWriteSettingsPermission() {
        DuAlertDialog.Builder builder = new DuAlertDialog().createBuilder(this);
        final AlertDialog alertDialog = builder.create();
        alertDialog.setMessage("请为应用授权修改系统设置权限");
        alertDialog.setButton(DialogInterface.BUTTON_POSITIVE
                , "去设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        try {
                            Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
                            intent.setData(Uri.parse("package:" + getPackageName()));
                            startActivityForResult(intent, REQUEST_CODE_WRITE_SETTINGS);
                        } catch (ActivityNotFoundException e) {
                            ConsoleLogger.printException(this.getClass(), e);
                        }
                    }
                });
        alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE
                , getResources().getString(R.string.permission_cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        alertDialog.dismiss();
                    }
                });
        alertDialog.show();
    }

    private void onGotWriteSettingsPermission() {
        if (duerlinkDiscoveryManager != null) {
            duerlinkDiscoveryManager.startApDiscovery(getApDiscoveryListener());
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_LOCATION_SETTINGS) {
            if (DemoUtils.isLocationEnabled(this)) {
                onLocationSettingEnabled();
            }
        } else if (requestCode == REQUEST_CODE_WRITE_SETTINGS) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Settings.System.canWrite(this)) {
                onGotWriteSettingsPermission();
            }
        }
    }
}
